public class Test7 {
    public static void main(String[] args) {
        int[][] arr = {{1,1,1}, {1,1,0}, {1,0,1}};
        floodFill(arr, 1, 1, 2);

    }

    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    static int m, n;
    static int genColor;
    static boolean[][] vis;
    public static int[][] floodFill(int[][] image, int sr, int sc, int color) {
        m = image.length;
        n = image[0].length;
        vis = new boolean[m][n];
        genColor = image[sr][sc];
        image[sr][sc] = color;
        vis[sr][sc] = true;
        dfs(image, sr, sc, color);
        return image;
    }

    public static void dfs(int[][] image, int sr, int sc, int color) {
         boolean b = false;
         for(int i = 0; i < 4; i++) {
             int x = dx[i] + sr;
             int y = dy[i] + sc;
             if(x >= 0 && x < m && y >= 0 && y < n && image[x][y] == genColor && vis[x][y] == false) {
                 b = true;
             }
         }
         if(b == false) {
             return;
         }

        for (int i = 0; i < 4; i++) {
            int x = dx[i] + sr;
            int y = dy[i] + sc;
            if (x >= 0 && x < m && y >= 0 && y < n && image[x][y] == genColor && vis[x][y] == false) {
                vis[x][y] = true;
                image[x][y] = color;
                dfs(image, x, y, color);
//                vis[x][y] = false;
            }
        }
    }
}
